import { View } from '@tarojs/components';
import classnames from 'classnames';
import { useEffect, useState } from 'react';
import Taro, { getCurrentPages } from '@tarojs/taro';
import { AtIcon } from 'taro-ui';
import './index.scss';

interface IProps {
  title: Function | string;
  showBackBtn?: boolean;
  isFixed?: boolean;
  rightContent?: Function | string;
  style?: Object;
}

export default function ({ title, showBackBtn = true, isFixed, rightContent = '', style }: IProps) {
  const [barHeight, setBarHeight] = useState<number>(0);
  const goBack = () => {
    const pages = getCurrentPages();
    if (pages.length === 1) {
      Taro.switchTab({
        url: '/pages/home/index',
      });
    } else {
      Taro.navigateBack();
    }
  };
  useEffect(() => {
    //获取状态栏的高度
    Taro.getSystemInfo({
      success: function (res) {
        console.log(res.statusBarHeight);
        setBarHeight(res.statusBarHeight || 0);
      },
    });
  }, []);
  return (
    <View
      className={classnames('navbar-container', isFixed ? 'is-fixed' : '')}
      style={{ paddingTop: barHeight + 'px', ...style }}
    >
      <View className="navbar-content">
        <View className="back-btn">
          {showBackBtn && <AtIcon value="chevron-left" size="20" onClick={goBack} />}
        </View>
        <View className="nav-title">{typeof title === 'function' ? title() : title}</View>
        <View className="right-content">
          {typeof rightContent === 'function' ? rightContent() : rightContent}
        </View>
      </View>
    </View>
  );
}
